import React, { useEffect, useState } from 'react';
import { Table, Tag, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { getSubmissionByUserId } from '@/services/submission';
import type { Submission, ResultVOPageSubmission } from '@/types/openapi';


const SubmissionsPage: React.FC = () => {
  const navigate = useNavigate();
  const [data, setData] = useState<Submission[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(10);
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res: ResultVOPageSubmission = await getSubmissionByUserId('1', String(page), String(size));
      if (res.code === 200 && res.data) {
        setData(res.data.records || []);
        setTotal(res.data.total || 0);
      } else {
        message.error(res.message || '获取提交记录失败');
      }
    } catch (e) {
      message.error('请求异常');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [page, size]);

  return (
    <Table
      rowKey="submission_id"
      loading={loading}
      dataSource={data}
      pagination={{
        current: page,
        pageSize: size,
        total,
        onChange: (p, s) => {
          setPage(p);
          setSize(s);
        },
      }}
      columns={[
        {
          title: '提交 ID',
          dataIndex: 'submission_id',
          render: (text: string) => (
            <a onClick={() => navigate(`/result/${text}`)}>{text}</a>
          ),
        },
        { title: '题目 ID', dataIndex: 'problem_id' },
        { title: '语言', dataIndex: 'language' },
        {
          title: '状态',
          dataIndex: 'status',
          render: (text) => (
            <Tag
              color={text === 'ACCEPTED' ? 'green' : 'red'}
              icon={text === 'ACCEPTED' ? '✅' : '❌'}
            >
              {text}
            </Tag>
          ),
        },
        { title: '用时', dataIndex: 'timeUsed' },
        { title: '内存', dataIndex: 'memoryUsed' },
      ]}
    />
  );
};

export default SubmissionsPage;
